<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.username"
        placeholder="登录名"
        style="width: 120px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-input v-model="listQuery.name" placeholder="用户名" style="width: 120px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.tel" placeholder="电话" style="width: 120px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button v-if="isAdmin()" class="filter-item" type="primary" icon="el-icon-plus" @click="addRootUser">
        用户
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      border
      default-expand-all
      row-key="id"
      size="mini"
      :data="list"
      max-height="500px"
      highlight-current-row
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      style="width: 100%;"
    >
      <el-table-column label="用户名" prop="id" min-width="20%">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="登录名" min-width="12%" align="center">
        <template slot-scope="{row}">
          <span>{{ row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" min-width="12%" align="center">
        <template slot-scope="{row}">
          <span>{{ row.tel }}</span>
        </template>
      </el-table-column>
      <el-table-column label="微信" min-width="12%" align="center">
        <template slot-scope="{row}">
          <span>{{ row.wechat }}</span>
        </template>
      </el-table-column>
      <el-table-column label="支付宝" min-width="12%" align="center">
        <template slot-scope="{row}">
          <span>{{ row.alipay }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="32%" align="center">
        <template slot-scope="{row}">
          <el-button icon="el-icon-plus" type="primary" size="mini" @click="addChild(row)">
            子用户
          </el-button>
          <el-button v-if="isAdmin()" type="primary" size="mini" @click="manageRole(row)">
            角色
          </el-button>
          <el-button type="warning" size="mini" @click="editUser(row)">
            修改
          </el-button>
          <el-button v-if="row.id != '0000' && row.id != rootUserId" type="danger" size="mini" @click="deletUser(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :visible.sync="dialogRoleVisible" title="角色管理">
      <h3>用户：{{ currentUser.name }}</h3>
      <div>
        选择添加角色：
        <el-select
          v-model="selectedRoles"
          multiple
          filterable
          style="width: 300px;"
          remote
          reserve-keyword
          placeholder="请输入角色名"
          :remote-method="queryRolesByName"
          :loading="selectLoading"
        >
          <el-option
            v-for="item in selectRoles"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        <el-button type="primary" @click="addRolesToUser">
          添加
        </el-button>
      </div>
      <div class="tag-wrapper">
        <el-tag v-for="item in currentUserRoles" :key="item.id" class="tag-small" closable @close="removeRoleFromUser(item.id)">
          {{ item.name }}
        </el-tag>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogAddUserVisible" width="60%" title="添加用户" @closed="clearUserForm">
      <el-alert v-if="formAddUser.isAddChild" style="margin-bottom: 8px;" :closable="false" :title="formAddUser.adduserTitle" type="success" />
      <el-form ref="formAddUser" :model="formAddUser" :rules="formAddUserRules" label-width="80px">
        <el-form-item label="账号名" prop="username" required>
          <el-col :span="8">
            <el-form-item prop="username" :error="formAddUserError.username">
              <el-input v-model="formAddUser.username" autocomplete="off" placeholder="请输入3-12个英文和数字" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="密码" prop="password">
              <el-input v-model="formAddUser.password" type="password" autocomplete="off" placeholder="请输入至少包含一个数字、一个大写字母、一个小写字母的八位密码" />
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="用户名" prop="name" required="">
          <el-col :span="8">
            <el-form-item prop="name" :error="formAddUserError.name">
              <el-input v-model="formAddUser.name" autocomplete="off" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="手机" prop="tel">
              <el-input v-model="formAddUser.tel" autocomplete="off" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="微信号" prop="wechat">
          <el-col :span="10">
            <el-input v-model="formAddUser.wechat" />
          </el-col>
          <el-col :span="14">
            <el-form-item label="支付宝" prop="alipay">
              <el-input v-model="formAddUser.alipay" />
            </el-form-item>
          </el-col>
        </el-form-item>

        <el-form-item v-if="isAdmin()" label="角色" prop="roles">
          <el-select
            v-model="formAddUser.roles"
            multiple
            filterable
            remote
            reserve-keyword
            placeholder="请输入角色名"
            style="width: 100%;"
            :remote-method="queryRolesByName"
            :loading="selectLoading"
          >
            <el-option
              v-for="item in selectRoles"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogAddUserVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitFormAddUser">提交</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="dialogEditUserVisible" width="60%" title="修改用户信息" @closed="clearUserForm">
      <el-form ref="formEditUser" :model="formEditUser" :rules="formAddUserRules" label-width="80px">
        <el-form-item label="账号名" prop="username" required>
          <el-col :span="8">
            <el-form-item prop="username">
              <el-input v-model="formEditUser.username" disabled autocomplete="off" placeholder="请输入3-12个英文和数字" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="密码" prop="password">
              <el-input v-model="formEditUser.password" type="password" autocomplete="off" placeholder="请输入至少包含一个数字、一个大写字母、一个小写字母的八位密码" />
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="用户名" prop="name" required="">
          <el-col :span="8">
            <el-form-item prop="name" :error="formAddUserError.name">
              <el-input v-model="formEditUser.name" autocomplete="off" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="手机" prop="tel">
              <el-input v-model="formEditUser.tel" autocomplete="off" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="微信号" prop="wechat">
          <el-col :span="10">
            <el-input v-model="formEditUser.wechat" />
          </el-col>
          <el-col :span="14">
            <el-form-item label="支付宝" prop="alipay">
              <el-input v-model="formEditUser.alipay" />
            </el-form-item>
          </el-col>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogEditUserVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitFormEditUser">提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { Message } from 'element-ui'
import { toTree } from '@/utils'
import { fetchList, fetchRoles, addRoles, removeRole, addUser, deleteUser, editUser } from '@/api/user'
import { fetchList as queryRoles } from '@/api/role'

export default {
  name: 'User',
  data() {
    return {
      currentUser: {},
      currentUserRoles: [],
      dialogRoleVisible: false,
      dialogAddUserVisible: false,
      dialogEditUserVisible: false,
      listLoading: false,
      selectLoading: false,
      selectRoles: [],
      selectedRoles: [],
      list: [],
      listQuery: {
        username: '',
        name: '',
        tel: ''
      },
      formAddUser: {
        isAddChild: false,
        adduserTitle: '',
        pid: undefined,
        username: undefined,
        password: undefined,
        name: undefined,
        wechat: undefined,
        alipay: undefined,
        level: 1,
        tel: '',
        roles: []
      },
      formEditUser: {
        id: '',
        username: undefined,
        password: undefined,
        name: undefined,
        wechat: undefined,
        alipay: undefined,
        tel: ''
      },
      formAddUserRules: {
        username: [{ required: true, pattern: /^[a-zA-Z\d]{3,12}$/, message: '请输入3-12个英文和数字', trigger: ['change', 'blur'] }],
        password: [{ required: true, pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/, message: '请输入至少包含一个数字、一个大写字母、一个小写字母的八位密码', trigger: ['change', 'blur'] }],
        name: [{ required: true, message: '用户名不能为空', trigger: ['change', 'blur'] }],
        tel: [{ required: true, message: '手机号不能为空', trigger: ['change', 'blur'] }]
      },
      formAddUserError: {
        username: ''
      }
    }
  },
  computed: mapGetters({
    roles: 'roles',
    rootUserId: 'id'
  }),
  created() {
    this.getList()
  },
  methods: {
    isAdmin() { return this.roles.includes('admin') },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = toTree(response.data)
        this.listLoading = false
      }).catch(err => Message.error(err))
    },
    handleFilter() {
      this.getList()
    },
    addRootUser() {
      this.formAddUser.isAddChild = false
      this.formAddUser.pid = ''
      this.formAddUser.level = 1
      this.dialogAddUserVisible = true
    },
    addChild(row) {
      if (row.type === 1) {
        Message.error('支付平台创建的用户无法添加子用户')
        return
      }
      this.formAddUser.isAddChild = true
      this.formAddUser.pid = row.id
      this.formAddUser.adduserTitle = `给用户: ${row.name} 添加子用户`
      this.formAddUser.level = row.level + 1
      this.dialogAddUserVisible = true
    },
    editUser(row) {
      this.formEditUser.id = row.id
      this.formEditUser.username = row.username
      this.formEditUser.password = row.password
      this.formEditUser.name = row.name
      this.formEditUser.wechat = row.wechat
      this.formEditUser.alipay = row.alipay
      this.formEditUser.tel = row.tel
      this.dialogEditUserVisible = true
    },
    deletUser(user) {
      this.$confirm(`该操作将永久删除用户"${user.username}"及其子用户的所有相关信息,确定继续操作？`, '提示 ', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteUser(user.id).then(response => {
          Message.success('操作成功')
          this.getList()
        })
      })
    },
    queryRolesByName(name) {
      queryRoles({ name }).then(response => {
        const fileterList = response.data.list.filter(i0 => {
          const index = this.currentUserRoles.findIndex(i1 => i1.id === i0.id)
          return index === -1
        })
        this.selectRoles = fileterList
      })
    },
    manageRole(user) {
      this.dialogRoleVisible = true
      this.currentUser = user
      fetchRoles(user.id).then(response => { this.currentUserRoles = response.data })
    },
    getUserRoles(userId) {
      fetchRoles(this.currentUser.id).then(response => {
        this.currentUserRoles = response.data
      })
    },
    addRolesToUser() {
      addRoles(this.currentUser.id, this.selectedRoles).then(response => {
        this.getUserRoles(this.currentUser.id)
        Message.success('操作成功')
        this.selectedRoles = []
      })
    },
    removeRoleFromUser(id) {
      removeRole(this.currentUser.id, id).then(response => {
        this.getUserRoles(this.currentUser.id)
        Message.success('操作成功')
      })
    },
    clearUserForm() {
      this.$refs['formAddUser'].resetFields()
      this.$refs['formEditUser'].resetFields()
    },
    submitFormAddUser() {
      this.$refs['formAddUser'].validate((valid) => {
        if (valid) {
          addUser(this.formAddUser).then(response => {
            if (response.data === 'success') {
              this.dialogAddUserVisible = false
              Message.success('操作成功')
              this.getList()
            } else {
              this.formAddUserError.username = '重复账号'
            }
          })
        }
      })
    },
    submitFormEditUser() {
      this.$refs['formEditUser'].validate((valid) => {
        if (valid) {
          editUser(this.formEditUser).then(response => {
            this.dialogEditUserVisible = false
            Message.success('操作成功')
            this.getList()
          })
        }
      })
    }
  }
}
</script>

<style scoped>
</style>
